<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 上传文件
    const fileInput = document.getElementById('file-input');
    const uploadBtn = document.getElementById('upload-btn');

    uploadBtn.addEventListener('click', () => {
      const file = fileInput.files[0];
      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/upload');

      // 监听上传进度事件
      xhr.upload.addEventListener('progress', (event) => {
        const percent = event.loaded / event.total;
        console.log(`上传进度：${percent * 100}%`);
      });

      // 监听上传完成事件
      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          console.log('上传成功！');
        } else {
          console.error('上传失败！');
        }
      });

      // 监听上传错误事件
      xhr.addEventListener('error', () => {
        console.error('上传出错！');
      });

      // 监听上传取消事件
      xhr.addEventListener('abort', () => {
        console.warn('上传已取消！');
      });

      xhr.send(file);
    });

    // 下载文件
    const downloadBtn = document.getElementById('download-btn');

    downloadBtn.addEventListener('click', () => {
      const xhr = new XMLHttpRequest();
      xhr.open('GET', '/download');
      xhr.responseType = 'blob';

      // 监听下载进度事件
      xhr.addEventListener('progress', (event) => {
        const percent = event.loaded / event.total;
        console.log(`下载进度：${percent * 100}%`);
      });

      // 监听下载完成事件
      xhr.addEventListener('load', () => {
        if (xhr.status === 200) {
          const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
          const url = URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.download = 'app.exe';
          link.click();
          console.log('下载成功！');
        } else {
          console.error('下载失败！');
        }
      });

      // 监听下载错误事件
      xhr.addEventListener('error', () => {
        console.error('下载出错！');
      });

      // 监听下载取消事件
      xhr.addEventListener('abort', () => {
        console.warn('下载已取消！');
      });

      xhr.send();
    });

  </script>
</body>

</html>